<template>
  <el-select v-model="select" ref="selectElement" popper-class="dept-tree-select">
    <template #footer>
      <el-scrollbar max-height="300px">
        <el-tree :node-key="nodeKey" @check="handleNodeCheck" ref="treeElement" :show-checkbox="showCheckbox" :data="store.deptTree" @node-click="handleNodeClick" :highlight-current="true" />
      </el-scrollbar>
    </template>
  </el-select>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import store from '../../store/deptTree'

defineOptions({
  name: 'a-dept2'
})

interface Props {
  nodeKey?: string
  showCheckbox?: boolean
  check?: (data: DeptTree[]) => void
}
const props = withDefaults(defineProps<Props>(), {
  showCheckbox: true,
  nodeKey: 'id',
  check: () => {}
})
const selectElement = ref<SelectInstance | null>(null)
const treeElement = ref<TreeInstance | null>(null)

const model = defineModel<DeptTree[]>({ required: true, default: () => [] })
const select = ref('')
function handleNodeClick() {
  const e = selectElement.value!.$el
  e.getElementsByTagName('input')[0].click()
}

function handleNodeCheck() {
  const checkedNodes = treeElement.value!.getCheckedNodes(true) as DeptTree[]
  model.value = checkedNodes
  props.check(checkedNodes)
  select.value = checkedNodes.map((i) => i.label).join(',')
}

onMounted(() => {
  treeElement.value?.setCheckedKeys(model.value.map((i) => i.id))
  select.value = model.value.map((i) => i.label).join(',')

  watch(
    () => select.value,
    (newVal) => {
      if (!newVal) {
        model.value = []
        treeElement.value?.setCheckedKeys([])
      }
    }
  )
})

defineExpose({
  treeElement: treeElement
})
</script>

<style lang="scss">
.dept-tree-select {
  overflow: hidden;
  .el-select-dropdown__footer {
    border-top: 0px;
    padding: 0;
  }
  .el-select-dropdown__empty {
    display: none;
  }
}
</style>
